<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/7
 * Time: 11:53
 */

namespace plugin\admin\app\logic\admin;


use plugin\admin\app\common\Tree;
use plugin\admin\app\common\Util;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\admin\Admin;
use plugin\admin\app\model\admin\Role;
use plugin\admin\app\model\admin\Rule;
use plugin\admin\app\model\Option;
use support\Request;
use support\Response;

class AdminLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {

    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function getConfig()
    {
        $name = 'system_config';
        $config = Option::where('name', $name)->value('value');
        if (empty($config)) {
            $config = file_get_contents(base_path('plugin/admin/public/config/pear.config.json'));
            if ($config) {
                $option = new Option();
                $option->name = $name;
                $option->value = $config;
                $option->save();
            }
        }

        return json(json_decode($config, true));
    }

    public function getRuleMenu($request)
    {
        $roleIds = $request->curAdminInfo['role_ids'];
        $rules_strings = $roleIds ? Role::whereIn('id', $roleIds)->pluck('rules') : [];
        $rules = [];
        foreach ($rules_strings as $rule_string) {
            if (!$rule_string) {
                continue;
            }
            $rules = array_merge($rules, explode(',', $rule_string));
        }
        $types = $request->get('type', '0,1');
        $types = is_string($types) ? explode(',', $types) : [0, 1];
        $items = Rule::orderBy('weight', 'desc')->get()->toArray();

        $formatted_items = [];
        foreach ($items as $item) {
            $item['pid'] = (int)$item['pid'];
            $item['name'] = $item['title'];
            $item['value'] = $item['id'];
            $item['icon'] = $item['icon'] ? "layui-icon {$item['icon']}" : '';
            $formatted_items[] = $item;
        }

        $tree = new Tree($formatted_items);
        $tree_items = $tree->getTree();
        // 超级管理员权限为 *
        if (!in_array('*', $rules)) {
            $this->removeNotContain($tree_items, 'id', $rules);
        }
        $this->removeNotContain($tree_items, 'type', $types);
        $menus = $this->emptyFilter(Tree::arrayValues($tree_items));

        return $this->json(0, 'ok', $menus);
    }

    public function getInfo($request)
    {
        $admin = $request->curAdminInfo;
        $info = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'avatar' => $admin['avatar'],
            'email' => $admin['email'],
            'mobile' => $admin['mobile'],
            'isSupperAdmin' =>$this->isSupperAdmin(),
        ];

        return $this->json(0, 'ok' ,$info);
    }

    public function update(Request $request): Response
    {
        $allow_column = [
            'nickname' => 'nickname',
            'avatar' => 'avatar',
            'email' => 'email',
            'mobile' => 'mobile',
        ];

        $data = $request->post();
        $update_data = [];
        foreach ($allow_column as $key => $column) {
            if (isset($data[$key])) {
                $update_data[$column] = $data[$key];
            }
        }
        if (isset($update_data['password'])) {
            $update_data['password'] = Util::passwordHash($update_data['password']);
        }
        Admin::where('id', $request->curAdminId)->update($update_data);

        return $this->json(0);
    }

    public function password(Request $request): Response
    {
        $hash = Admin::find($request->curAdminId)['password'];
        $password = $request->post('password');
        if (!$password) {
            throw new AdminException(4020,'密码不能为空');
        }
        if ($request->post('password_confirm') !== $password) {
            throw new AdminException(4020,'两次密码输入不一致');
        }
        if (!Util::passwordVerify($request->post('old_password'), $hash)) {
            throw new AdminException(4020,'原始密码不正确');
        }
        $update_data = [
            'password' => Util::passwordHash($password)
        ];
        Admin::where('id', $request->curAdminId)->update($update_data);
        return $this->json(0);
    }


}